using Common;
using DAL;
using Model;
using System.Data;
namespace BLL {
    public class UserBLL {
        private UserDAL _userDal = UserDAL.GetInstance();

        #region 单例
        private UserBLL(){}
        private static UserBLL _userBll = null;
        public static UserBLL GetUserInfoBLL() {
            if (_userBll == null) {
                lock (typeof(UserBLL)) {
                    _userBll = new UserBLL();
                }
            }
            return _userBll;
        }
        #endregion
        
        public Result<User> ManagerLogin(User user) {
            Result<User> loginResult = UserLogin(user);

            if (loginResult.IsSuccess) {
                return loginResult.Data.Position != "经理" ? Result<User>.Error("user is not a manager.") : Result<User>.Ok(loginResult.Data);
            }
            return loginResult;
        }

        public Result<User> UserLogin(User user) {
            user.Password = MD5Encryptor.Encrypt(user.Password);
            User userLogin = _userDal.Login(user);

            return _userDal.Login(user) == null ? Result<User>.Error("username or password is incorrect.") : Result<User>.Ok(userLogin);
        }

        //查询所有员工
        public DataTable GetAllUsers() {
            return _userDal.SelectAllUsers();
        }

        //添加员工
        public Result<User> AddUser(User user) {
            user.Password = MD5Encryptor.Encrypt(user.Password);
            bool isSuccess = _userDal.InsertUser(user);
            return isSuccess ? Result<User>.Ok("add successful") : Result<User>.Error("add failed");
        }

        //更新员工信息
        public Result<User> UpdateUserInfo(User user) {
            user.Password = MD5Encryptor.Encrypt(user.Password);
            bool isSuccess = _userDal.UpdateUserInfo(user);
            return isSuccess ? Result<User>.Ok("update successful") : Result<User>.Error("update failed");
        }

        //根据id删除员工
        public Result<User> DeleteById(User user) {
            bool isSuccess = _userDal.DeleteById(user);
            return isSuccess ? Result<User>.Ok("delete successful") : Result<User>.Error("delete failed");
        }
    }
}